// admin/order-manage/order-manage.js
// const db = wx.cloud.database(); // <-- ***删除：不再直接访问数据库***
const util = require('../../utils/util.js');

Page({
  data: {
    orders: [],
    loading: true,
  },

  onShow: function () {
    this.getOrders();
  },

  // --- *** 修改：使用云函数获取列表 *** ---
  getOrders: function() {
    this.setData({ loading: true });
    wx.cloud.callFunction({
      name: 'manageorders',
      data: {
        action: 'getList'
      }
    }).then(res => {
      if (res.result.success) {
        const orders = res.result.data;
        orders.forEach(order => {
          order.createTimeFormatted = util.formatTime(new Date(order.createTime));
        });
        this.setData({
          orders: orders,
          loading: false
        });
      } else {
        this.setData({ loading: false });
        wx.showToast({ title: res.result.message || '加载失败', icon: 'none' });
      }
    }).catch(err => {
      this.setData({ loading: false });
      wx.showToast({ title: '加载失败', icon: 'none' });
      console.error(err);
    });
  },

  // --- *** 修改：使用云函数更新状态 *** ---
  updateStatus: function(e) {
    const orderId = e.currentTarget.dataset.id;
    const currentStatus = e.currentTarget.dataset.status;
    const newStatus = currentStatus === 'pending' ? 'printing' : 'completed';

    wx.showModal({
      title: '确认操作',
      content: `确定要将订单状态更新为 "${newStatus === 'printing' ? '打印中' : '已完成'}" 吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '更新中...' });
          wx.cloud.callFunction({
            name: 'manageorders', // <-- ***已修正为新函数***
            data: {
              action: 'updateStatus', // <-- ***指定 action ***
              orderId: orderId,
              status: newStatus
            }
          }).then((res) => {
            wx.hideLoading();
            if (res.result.success) {
              wx.showToast({ title: '更新成功' });
              this.getOrders();
            } else {
              wx.showToast({ title: res.result.message || '更新失败', icon: 'none' });
            }
          }).catch(() => {
            wx.hideLoading();
            wx.showToast({ title: '更新失败', icon: 'none' });
          });
        }
      }
    });
  },

  downloadFile: function(e) {
    const fileUrl = e.currentTarget.dataset.url;
    // (下载文件逻辑保持不变，这是合法的)
    wx.cloud.downloadFile({
      fileID: fileUrl,
      success: res => {
        wx.openDocument({
          filePath: res.tempFilePath,
          showMenu: true,
          success: function (res) {
            console.log('打开文档成功')
          }
        })
      },
      fail: console.error
    })
  }
});